package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Spot;
import cn.wolfcode.wolf2w.query.SpotQuery;
import cn.wolfcode.wolf2w.repository.SpotRepository;
import cn.wolfcode.wolf2w.service.ISpotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
//@Transactional mongodb事务必须复制集方式
public class SpotServiceImpl implements ISpotService{

    @Autowired
    private SpotRepository repository;

    @Autowired
    private MongoTemplate template;


    @Override
    public void save(Spot spot) {
        spot.setId(null);//不让mongod误会：
        repository.save(spot);
    }

    @Override
    public void update(Spot spot) {
        repository.save(spot);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Spot get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Spot> list() {
        return repository.findAll();
    }

    @Override
    public Page<Spot> query(SpotQuery qo) {
        //Page  核心：currentpage pagesize total list totalPage  next pre

        //MQL 语句拼接类  查询封装类
        Query query=new Query();
        //拼接条件
        long total=template.count(query, Spot.class);
        if (total == 0) {
            return Page.empty();//空地分页对象
        }
        //当前页显示数据list：select*from xxxwhere。。。limit？,？
        Pageable pageable=PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        query.with(pageable);
        List<Spot> list=template.find(query, Spot.class);
        return new PageImpl<Spot>(list, pageable, total);//PageImpl代替计算
        //return DBHelper.query(template, Spot.class, query, pageable);
    }

    @Override
    public void saveOrUpdate(Spot spot) {
//字符串id必须实现下面操作
        if (StringUtils.hasLength(spot.getId())) {
            //update
            //特殊案例, 页面更新的数据, 刚好跟集合中字段个数一致
            //所以这种等价于全量更新
            this.update(spot);
        } else {
            //save
            this.save(spot);
        }
    }


}
